package cn.iocoder.yudao.module.system.service.ai;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.ai.vo.AiAdmissionCutoffScoreCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.ai.vo.AiAdmissionCutoffScorePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.ai.vo.AiAdmissionCutoffScoreUpdateReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.ai.AiAdmissionCutoffScoreDO;
import cn.iocoder.yudao.module.system.dal.dataobject.college.CollegeDO;
import cn.iocoder.yudao.module.system.dal.mysql.ai.AiAdmissionCutoffScoreMapper;
import cn.iocoder.yudao.module.system.dal.mysql.college.CollegeMapper;
import cn.iocoder.yudao.module.system.util.SchoolNameUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.AI_ADMISSION_CUTOFF_SCORE_NOT_EXISTS;

/**
 * AI 录取分数线 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class AiAdmissionCutoffScoreServiceImpl implements AiAdmissionCutoffScoreService {

    @Resource
    private AiAdmissionCutoffScoreMapper aiAdmissionCutoffScoreMapper;

    @Resource
    private CollegeMapper collegeMapper;

    @Override
    public Long createAiAdmissionCutoffScore(AiAdmissionCutoffScoreCreateReqVO createReqVO) {
        // 插入
        AiAdmissionCutoffScoreDO aiAdmissionCutoffScore = BeanUtils.toBean(createReqVO, AiAdmissionCutoffScoreDO.class);
        aiAdmissionCutoffScoreMapper.insert(aiAdmissionCutoffScore);
        // 返回
        return aiAdmissionCutoffScore.getId();
    }

    @Override
    public void updateAiAdmissionCutoffScore(AiAdmissionCutoffScoreUpdateReqVO updateReqVO) {
        // 校验存在
        validateAiAdmissionCutoffScoreExists(updateReqVO.getId());
        // 更新
        AiAdmissionCutoffScoreDO updateObj = BeanUtils.toBean(updateReqVO, AiAdmissionCutoffScoreDO.class);
        aiAdmissionCutoffScoreMapper.updateById(updateObj);
    }

    @Override
    public void deleteAiAdmissionCutoffScore(Long id) {
        // 校验存在
        validateAiAdmissionCutoffScoreExists(id);
        // 删除
        aiAdmissionCutoffScoreMapper.deleteById(id);
    }

    private void validateAiAdmissionCutoffScoreExists(Long id) {
        if (aiAdmissionCutoffScoreMapper.selectById(id) == null) {
            throw exception(AI_ADMISSION_CUTOFF_SCORE_NOT_EXISTS);
        }
    }

    @Override
    public AiAdmissionCutoffScoreDO getAiAdmissionCutoffScore(Long id) {
        return aiAdmissionCutoffScoreMapper.selectById(id);
    }

    @Override
    public PageResult<AiAdmissionCutoffScoreDO> getAiAdmissionCutoffScorePage(AiAdmissionCutoffScorePageReqVO pageReqVO) {
        return aiAdmissionCutoffScoreMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AiAdmissionCutoffScoreDO> getAiAdmissionCutoffScoreListBySchoolName(String schoolName, String province, String batchName) {
        return aiAdmissionCutoffScoreMapper.selectListBySchoolName(schoolName, province, batchName);
    }

    @Override
    public List<AiAdmissionCutoffScoreDO> getAiAdmissionCutoffScoreListBySchoolNameAndType(String schoolName, String type, String province, String batchName) {
        return aiAdmissionCutoffScoreMapper.selectListBySchoolNameAndType(schoolName, type, province, batchName);
    }

    @Override
    public String syncSchoolUuid() {
        long startTime = System.currentTimeMillis();
        log.info("【同步院校UUID】开始执行...");

        // 1. 查询所有AI录取分数线数据
        QueryWrapper<Object> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("school_uuid", null);
        List<AiAdmissionCutoffScoreDO> allCutoffScores = aiAdmissionCutoffScoreMapper.selectList();
        if (allCutoffScores == null || allCutoffScores.isEmpty()) {
            log.warn("【同步院校UUID】AI录取分数线表为空，无需同步");
            return "AI录取分数线表为空，无需同步";
        }
        log.info("【同步院校UUID】查询到AI录取分数线记录数：{}", allCutoffScores.size());

        // 2. 查询所有学校信息
        List<CollegeDO> allColleges = collegeMapper.selectList();
        if (allColleges == null || allColleges.isEmpty()) {
            log.warn("【同步院校UUID】学校表为空，无法同步");
            return "学校表为空，无法同步";
        }
        log.info("【同步院校UUID】查询到学校记录数：{}", allColleges.size());

        // 3. 构建学校名称变体映射 Map<学校名称变体, CollegeDO>
        Map<String, CollegeDO> schoolNameVariantMap = new HashMap<>();
        for (CollegeDO college : allColleges) {
            if (StrUtil.isBlank(college.getCollegeName())) {
                continue;
            }
            // 为每个学校生成所有名称变体
            Set<String> variants = SchoolNameUtils.generateSchoolNameVariants(college.getCollegeName());
            for (String variant : variants) {
                // 如果多个学校有相同的变体，保留第一个（一般不会出现这种情况）
                schoolNameVariantMap.putIfAbsent(variant, college);
            }
        }
        log.info("【同步院校UUID】生成学校名称变体映射数：{}", schoolNameVariantMap.size());

        // 4. 遍历AI录取分数线，匹配学校UUID
        int matchedCount = 0;
        int updatedCount = 0;
        int unmatchedCount = 0;
        List<String> unmatchedSchoolNames = new ArrayList<>();

        for (AiAdmissionCutoffScoreDO cutoffScore : allCutoffScores) {
            if (StrUtil.isBlank(cutoffScore.getSchoolName())) {
                continue;
            }

            // 生成当前学校名称的所有变体，尝试匹配
            Set<String> variants = SchoolNameUtils.generateSchoolNameVariants(cutoffScore.getSchoolName());
            CollegeDO matchedCollege = null;

            for (String variant : variants) {
                matchedCollege = schoolNameVariantMap.get(variant);
                if (matchedCollege != null) {
                    break; // 找到匹配，退出循环
                }
            }

            if (matchedCollege != null) {
                // 匹配成功
                matchedCount++;
                String newSchoolUuid = matchedCollege.getSchoolUuid();

                // 判断是否需要更新
                if (!StrUtil.equals(cutoffScore.getSchoolUuid(), newSchoolUuid)) {
                    // 更新schoolUuid
                    AiAdmissionCutoffScoreDO updateObj = new AiAdmissionCutoffScoreDO();
                    updateObj.setId(cutoffScore.getId());
                    updateObj.setSchoolUuid(newSchoolUuid);
                    aiAdmissionCutoffScoreMapper.updateById(updateObj);
                    updatedCount++;

                    if (updatedCount <= 10) { // 只打印前10条
                        log.info("【同步院校UUID】更新：AI分数线学校={}，匹配到学校={}，UUID={}",
                                cutoffScore.getSchoolName(), matchedCollege.getCollegeName(), newSchoolUuid);
                    }
                }
            } else {
                // 未匹配
                unmatchedCount++;
                if (unmatchedSchoolNames.size() < 20) { // 只记录前20个未匹配的
                    unmatchedSchoolNames.add(cutoffScore.getSchoolName());
                }
            }
        }

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        // 5. 输出统计结果
        String result = String.format(
                "同步完成！总记录数=%d，匹配成功=%d，实际更新=%d，未匹配=%d，耗时=%dms",
                allCutoffScores.size(), matchedCount, updatedCount, unmatchedCount, duration
        );
        log.info("【同步院校UUID】{}", result);

        if (unmatchedCount > 0) {
            log.warn("【同步院校UUID】未匹配的学校名称（前{}个）：{}", 
                    Math.min(20, unmatchedCount), String.join(", ", unmatchedSchoolNames));
        }

        return result;
    }

}